package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"shorten/global"
	"shorten/pkg/tracer"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"

	"shorten/internal/dao"
	"shorten/internal/routers"
	"shorten/internal/service"
	"shorten/pkg/logging"
	"shorten/pkg/setting"
)

func init() {
	err := setupSettings()
	if err != nil {
		panic("配置文件初始化失败:" + err.Error())
	}
	err = setupLogger()
	if err != nil {
		panic("日志初始化失败:" + err.Error())
	}
	err = setupTrans()
	if err != nil {
		panic("语言包初始化失败:" + err.Error())
	}
	err = setupDBEngine()
	if err != nil {
		panic("数据库初始化失败:" + err.Error())
	}
	err = setupRDB()
	if err != nil {
		panic("redis初始化失败:" + err.Error())
	}
	err = setupTracer()
	if err != nil {
		panic("tracer初始化失败:" + err.Error())
	}
}

func main() {
	cfg := setting.Settings.Server
	gin.SetMode(cfg.RunMode)
	//启动web服务
	router := routers.NewRouter()
	srv := http.Server{
		Addr:    cfg.HttpHost + ":" + cfg.HttpPort,
		Handler: router,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	//退出信号等待
	<-quit
	//关闭web服务（设置 5 秒的超时时间）
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Shutting down server...")
}

// 初始化配置
func setupSettings() error {
	cfg, err := setting.NewSetting("./conf/config.yaml")
	if err != nil {
		return err
	}
	return cfg.ReadConf(&setting.Settings)
}

// 初始化日志服务
func setupLogger() error {
	return logging.InitLog(setting.Settings.Log)
}

func setupTrans() error {
	return service.InitTrans("zh")
}

// 初始化
func setupDBEngine() error {
	return dao.InitDBEngine(setting.Settings.Database)
}

// 初始化redis
func setupRDB() error {
	return dao.InitRDB(setting.Settings.Redis)
}

func setupTracer() error {
	jaegerTracer, _, err := tracer.NewJaegerTracer(
		"shorten",
		"127.0.0.1:6831",
	)
	if err != nil {
		return err
	}
	global.Tracer = jaegerTracer
	return nil

}
